package com.gaoboy.springbootgoods.service.impl;

import com.gaoboy.springbootgoods.entity.Goods;
import com.gaoboy.springbootgoods.entity.Order;
import com.gaoboy.springbootgoods.entity.OrderItem;
import com.gaoboy.springbootgoods.exception.AppException;
import com.gaoboy.springbootgoods.mapper.GoodsMapper;
import com.gaoboy.springbootgoods.mapper.OrderItemMapper;
import com.gaoboy.springbootgoods.mapper.OrderMapper;
import com.gaoboy.springbootgoods.service.OrderService;
import com.gaoboy.springbootgoods.utils.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;


    @Override
    @Transactional
    public String saveOrder(int[] id) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        Integer userId = HttpUtil.threadLocal.get();

        //根据id查询商品
        List<Goods>goods = goodsMapper.queryByIds(id);

        //生成订单对象
        Order order = new Order();
        //订单总价
        Integer totalprice=0;

        String orderNum = dateFormat.format(new Date());
        order.setOrdernum(orderNum);
        order.setCreatetime(new Date());
        order.setExpiretime(new Date(new Date().getTime()+3*60*1000));
        order.setValid(1);
        order.setUserId(userId);
        for (Goods good : goods){
            totalprice+=good.getPPrice();
        }
        order.setTotalprice(totalprice);

        //将生成的订单对象保存到数据表
        orderMapper.insert(order);

        //之后将订单明细保存到明细表
        List<OrderItem> orderItemList = goods.stream().map(item ->{
            OrderItem orderItem = new OrderItem();
            orderItem.setPid(item.getId());
            orderItem.setOrdernum(orderNum);
            return orderItem;
        }).collect(Collectors.toList());

        orderItemMapper.insert(orderItemList);

        //减商品数量
        for (int prodId: id){
            int result = goodsMapper.reduceStock(prodId);
            if (result==0){
                throw new AppException("部分商品数量不足,无法生成订单");
            }
        }
        //threadlocal中的值在使用完后马上remove，避免造成内存泄露
        HttpUtil.threadLocal.remove();
        return orderNum;
    }

    @Override
    public List<Order> queryByUserId(Integer userId) {
        return orderMapper.queryByUserId(userId);
    }
}
